package com.onlinemarket.thrid.daoimpl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.onlinemarket.thrid.dao.StroageDao;
import com.onlinemarket.thrid.domain.Goods;
import com.onlinemarket.thrid.domain.Stroage;

@Repository
public class StroageDaoImpl implements StroageDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");

	@Override
	public boolean addstorage(Stroage s) {
		int updatenubmer = 0;
		// String sql = "INSERT into stroage (stroage_number,stroage_date,goods_id)
		// VALUES (67,'2018-01-02 11:11:10',4)";
		String sql = "INSERT into stroage (stroage_number,stroage_date,goods_id) VALUES (?,?,?)";
		try {
			updatenubmer = jdbcTemplate.update(sql,
					new Object[] { s.getStroage_number(), format.parse(s.getStroage_date()), s.getGoods_id() });
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return updatenubmer == 1 ? true : false;
	}

	@Override
	public List<Goods> getallGoods() {
		List<Goods> allgoods = new ArrayList<Goods>();
		String sql = "SELECT goods_id,goods_name from goods;";
		List<Map<String, Object>> goodslist = jdbcTemplate.queryForList(sql);
		Iterator<Map<String, Object>> iterator = goodslist.iterator();
		while (iterator.hasNext()) {
			Map<String, Object> map = iterator.next();
			Goods goods = new Goods();
			goods.setGoods_id(Integer.parseInt(map.get("goods_id").toString()));
			goods.setGoods_name(map.get("goods_name").toString());
			allgoods.add(goods);
		}

		return allgoods;
	}

}
